/**
 * 
 */
package com.rtsp.tool.snatch04;

import java.awt.image.BufferedImage;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.opencv_core.Mat;

/**
 * @author w.weizhen
 * 
 */
public class RtspSnatchRunnable04  implements Runnable{
	
//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) 
//	{
//		
//	}
	
	private String code;
	// 工作目录
	private final String user_dir = System.getProperty("user.dir") + File.separator;
	private final String data_path = user_dir + "data" + File.separator;
	private String dateTimeFormatter = null;
	
	public FFmpegFrameGrabber grabber;
	
	RtspSnatchRunnable04(String code, String rtsp_url)
	{
		this.code = code;
//		data_path = data_path + code + File.separator;
		
		try {
			grabber = new FFmpegFrameGrabber(rtsp_url);
			grabber.setOption("stimeout", 5 * 1000 * 1000 + "");// 增加超时参数[单位是微秒，1秒=1000*1000微秒]
			grabber.setOption("Connection", "keep-alive");// 
			grabber.setImageWidth(1920);// 画面宽度
			grabber.setImageHeight(1080);// 画面高度
//			grabber.setImageWidth(960);// 画面宽度
//			grabber.setImageHeight(540);// 画面高度
			
//			grabber.setFrameRate(20);// 画面帧率
			
//			grabber.setVideoBitrate(10000);
//			grabber.setOption("g", "2");
//			grabber.setOption("bufsize", "10000");
//			grabber.setNumBuffers(0);
			
			// 设置缓存大小，提高画质、减少卡顿花屏
			grabber.setOption("buffer_size", "1024000");
			
			grabber.setFormat("rtsp");
			// 设置rtsp传输协议为udp传输模式
			grabber.setOption("rtsp_transport", "tcp");
			// 首选TCP进行RTP传输
			grabber.setOption("rtsp_flags", "prefer_tcp");
			
//			grabber.startUnsafe();
			grabber.start();
//			grabber.stop();
//			grabber.restart();
			
			// 只打印错误日志
			// 这里程序有一个问题，Javacv记录摄像机流，控制台一直打印警告bytedeco/javacpp-presets
			// 这个问题我翻看了作者在GitHub的回答，问题至少是从2017年开始发现的，没有解决，没有被作为一个被重视的‘问题’
			// https://github.com/bytedeco/javacpp-presets/issues/461
			// https://github.com/bytedeco/javacv/issues/780
			// https://github.com/bytedeco/javacv/issues/1283
			avutil.av_log_set_level(6);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//	private void play()
//	{
//		try {
//			CanvasFrame canvasFrame = new CanvasFrame("摄像机");
//	        canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//	        canvasFrame.setAlwaysOnTop(true);
//	        OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
//	        while (true){
//	            Frame frame = grabber.grabImage();
//	            Mat mat = converter.convertToMat(frame);
//	            canvasFrame.showImage(frame);
//	        }
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	private String path()
	{
		dateTimeFormatter = "yyyy-MM-dd"+ File.separator +"HH-mm";
		String file_absolute = data_path + code + File.separator + LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateTimeFormatter));
		File file = new File(file_absolute);
		if(!file.exists())
		{
			file.mkdirs();
		}
		return file_absolute;
	}
	
	@Override
	public void run() 
	{
		try {
			String file_absolute = path();
			
			Frame frame = grabber.grabImage();//获取帧图片，不包含音频
////		Frame frame = grabber.grabFrame();
////		Frame frame = grabber.grab();//包含音频
			
			if (frame != null) {
				try {
					Java2DFrameConverter converter = new Java2DFrameConverter();
					BufferedImage bi = converter.getBufferedImage(frame.clone());
					File outPut = new File(file_absolute + File.separator + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss_SSS")) + ".jpeg");
					ImageIO.write(bi, "jpeg", outPut);
					bi.flush();
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					frame.close();
				}
			}
			else
			{
				grabber.restart();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建BufferedImage对象
	 */
	public BufferedImage FrameToBufferedImage(Frame frame) {
		Java2DFrameConverter converter = new Java2DFrameConverter();
		BufferedImage bufferedImage = converter.getBufferedImage(frame);
//		bufferedImage=rotateClockwise90(bufferedImage);//将图片旋转90度
		return bufferedImage;
	}

	/**
	 * 处理图片，将图片旋转90度。
	 */
	public BufferedImage rotateClockwise90(BufferedImage bi) {
		int width = bi.getWidth();
		int height = bi.getHeight();
		BufferedImage bufferedImage = new BufferedImage(height, width, bi.getType());
		for (int i = 0; i < width; i++)
			for (int j = 0; j < height; j++)
				bufferedImage.setRGB(j, i, bi.getRGB(i, j));
		return bufferedImage;
	}
}